const { Service } = require("egg");

class UserService extends Service {
  async create(value) {
    const { ctx } = this;
    const isExists = await ctx.model.ArticleClassify.findOne({
      where: { value },
    });
    if (isExists) {
      return isExists;
    }
    return await ctx.model.ArticleClassify.create({
      value,
    });
  }
  async createOrUpdate(value, key) {
    const { ctx } = this;
    if (key) {
      const classify = await ctx.model.ArticleClassify.findOne({
        where: { key },
      });

      Object.assign(classify, { value });
      return await classify.save();
    } else {
      const isExists = await ctx.model.ArticleClassify.findOne({
        where: { value },
      });
      if (isExists) {
        throw new Error("信息来源已存在");
      }
      return await ctx.model.ArticleClassify.create({
        value,
      });
    }
  }

  async list() {
    const datas = await this.ctx.model.ArticleClassify.findAll({
      raw: true,
      where: {
        isDeleted: 0,
      },
    });
    return datas;
  }
}

module.exports = UserService;
